package com.dmgis.qxfw.dataservice.businessservice.yydl.controller;

import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.all_today_forecast;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.all_today_forecasts;

import com.dmgis.qxfw.dataservice.businessservice.common.entity.DocFile;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.HourPower;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.MsgMedium;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.yydl.service.HourPowerServiceI;
import com.dmgis.qxfw.dataservice.businessservice.yydl.service.Impl.DayForecastServiceImpl;
import com.dmgis.qxfw.dataservice.businessservice.yydl.service.UtilServiceI;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/xtdl")
public class HourPowerController {
	private  final String operatingSystem;

	@Autowired
	public HourPowerController(String operatingSystem) {
		this.operatingSystem = operatingSystem;
	}

	String temp = "";

	MongoService1 ms = new MongoService1();

	@Autowired
	private HourPowerServiceI hourPowerServiceImpl;

	@Autowired
	private DayForecastServiceImpl dayForecastServiceImpl;

	@Autowired
	private UtilServiceI utilServiceImpl;

	// 初始化逐小时负荷预报最新时间
	@RequestMapping("/initHourPowerLoadTime")
	@ResponseBody
	public String initHourPowerLoadTime() {
		Date date = hourPowerServiceImpl.initHourPowerLoadTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		temp = sdf.format(date);
		return temp;
	}

	// 逐小时负荷预报产品初始化最新时间
	@RequestMapping("/initHourPowerLoadTime2")
	@ResponseBody
	public String initHourPowerLoadTime2() {
		Date date = hourPowerServiceImpl.initHourPowerLoadTime2();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar rightNow = Calendar.getInstance();
		rightNow.setTime(date);
		rightNow.add(Calendar.DAY_OF_YEAR, -3);
		Date date2 = rightNow.getTime();
		String d1 = sdf.format(date);
		String d2 = sdf.format(date2);
		temp = d2 + "|" + d1;
		return temp;
	}

	// 获取小时电力负荷预报数据
	@RequestMapping("/hourPowerLoad")
	@ResponseBody
	public String hourPowerLoad(HttpServletRequest requqest) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		Calendar cal = sdf.getCalendar();
		String dateTime = requqest.getParameter("dateTime");
		List<HourPower> hpList = hourPowerServiceImpl.hourPowerLoad(dateTime);
		String tableData = "[";
		String xValue = "[";
		String yValue = "[";
		for (HourPower hp : hpList) {
			String str = sdf.format(hp.getDataChar());
			String hour = String.valueOf(cal.get(Calendar.HOUR));
			tableData += "{\"dateChar\":\"" + str + "\",\"powerLoad\":\"" + hp.getLoad() + "\"},";
			xValue += "'" + hour + "',";
			yValue += Double.parseDouble(hp.getLoad().trim()) + ",";
		}
		if (tableData.endsWith(",")) {
			tableData = tableData.substring(0, tableData.length() - 1);
		}
		tableData = tableData + "]";
		if (xValue.endsWith(",")) {
			xValue = xValue.substring(0, xValue.length() - 1);
		}
		xValue = xValue + "]";
		if (yValue.endsWith(",")) {
			yValue = yValue.substring(0, yValue.length() - 1);
		}
		yValue = yValue + "]";
		yValue = "[{name:'"+DbConfig.CITY+"',data:" + yValue + "}]";
		temp = tableData + "|" + xValue + "|" + yValue + "|" + getDayForecast(dateTime);
		if (temp.isEmpty() || temp == null) {
			return "Todo";
		}
		return temp;
	}

	@RequestMapping("/getTodayForecast")
	@ResponseBody
	public Object getDayForecast() throws Exception {
		HashMap<String, Object> map = new HashMap<>();
		map.put("todayForecastList", dayForecastServiceImpl.getTodayForecast());

		List<all_today_forecast> re = dayForecastServiceImpl.getAllTodayForecast();
		WebCtrlData wcd = new WebCtrlData();
		ArrayList<all_today_forecasts> allTodayForecasts = new ArrayList<>();

		for (int i = 0; i < re.size(); i++) {
			String areaname = re.get(i).getAreaname();
			String stationid = re.get(i).getStationid();
			Double humid = re.get(0).getHumid();
			Double rain = re.get(0).getRain();
			Double maxtemp = re.get(0).getMaxtemp();
			String windd = WebCtrlData.GetAllFx(re.get(i).getWindd().toString().replace("-65535", "0").trim());
			String winds =wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(re.get(i).getWinds())));
			all_today_forecasts allToday = new all_today_forecasts();
			allToday.setAreaname(areaname);
			allToday.setStationid(stationid);
			allToday.setHumid(humid);
			allToday.setRain(rain);
			allToday.setMaxtemp(maxtemp);
			allToday.setWindd(winds);
			allToday.setWinds(windd);
			allTodayForecasts.add(allToday);
		}
		map.put("alltodayForecast", allTodayForecasts);
		return map;
	}


	// 当天天气预报
	public String getDayForecast(String date) throws ParseException {
		WebCtrlData wcd = new WebCtrlData();
		String result = "[";
		String maxResult = "[";
		double maxTemp = -65535, minTemp = -65535, maxHumid = -65535;
		String strWeather = "";
		List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowdayTime = sdf.format(new Date());
		Date d = sdf.parse(nowdayTime);

		Calendar calc = Calendar.getInstance();
		calc.setTime(sdf.parse(date));
		calc.add(calc.DATE, 30);
		Date newDate = calc.getTime();

		if (date != null && date != "") {
			if (newDate.before(d)) {
				map = dayForecastServiceImpl.getDayForecast1(date);
			} else {
				map = dayForecastServiceImpl.getDayForecast(date);
			}
		}
		if ((!map.isEmpty()) && map != null) {
			for (int i = 0; i < map.size(); i += 2) {
				Map<String, Object> m = map.get(i);
				String stationName = m.get("stationname").toString().trim();
				String weather1 = m.get("weather1").toString().trim();
				String weather2 = map.get(i + 1).get("weather1").toString().trim();
				String wcode1 = wcd.WeatherNameToPicPath(weather1);
				String wcode2 = wcd.WeatherNameToPicPath(weather2);
				double speed1 = 0;
				try {
					Object tempString = m.get("winds");
					speed1 = Double.parseDouble(tempString.toString());
				} catch (Exception e) {
					System.err.println(e.getStackTrace());
				}
				String windS1 = wcd.GetWeatherFs(String.valueOf(wcd.FengSuToFengJi(speed1)));
				String s = map.get(i + 1).get("winds").toString().trim();
				String windS2 = wcd.GetWeatherFs(String.valueOf(wcd.FengSuToFengJi(Double.valueOf(s))));
				String windD1 = wcd.GetAllFx(m.get("windd").toString().trim());
				int index;
				if ((index = stationName.indexOf("乡")) > 0 || (index = stationName.indexOf("镇")) > 0) {
					stationName = stationName.substring(0, index + 1);
				}
				String maxTemp1 = m.get("maxtemp").toString();
				String maxTemp2 = map.get(i + 1).get("maxtemp").toString();
				String minTemp1 = m.get("mintemp").toString();
				String minTemp2 = map.get(i + 1).get("mintemp").toString();
				result += "{";
				result += "\"stationname\":\"" + stationName + "\",";
				result += "\"pic1\":\"" + wcode1 + "\",";
				result += "\"pic2\":\"" + wcode2 + "\",";
				double maxT = (Double.valueOf(maxTemp1) > Double.valueOf(maxTemp2) ? Double.valueOf(maxTemp1)
						: Double.valueOf(maxTemp2));
				if (maxT == -65535) {
					maxTemp = maxT;
				} else {
					maxTemp = (maxT > maxTemp ? maxT : maxTemp);
				}
				double minT = (Double.valueOf(minTemp1) > Double.valueOf(minTemp2) ? Double.valueOf(minTemp2)
						: Double.valueOf(minTemp1));
				if (minT == -65535) {
					minTemp = minT;
				} else {
					minTemp = (minT < minTemp ? minT : minTemp);
				}
				String maxHumid1 = m.get("humid").toString();
				String maxHumid2 = m.get("humid").toString();
				double maxH = (Double.valueOf(maxHumid1) > Double.valueOf(maxHumid2) ? Double.valueOf(maxHumid1)
						: Double.valueOf(maxHumid2));
				if (maxH == -65535) {
					maxHumid = maxH;
				} else {
					maxHumid = (maxH > maxHumid ? maxH : maxHumid);
				}
				result += "\"maxtemp\":\"" + (Double.valueOf(maxTemp1) > Double.valueOf(maxTemp2) ? maxTemp1 : maxTemp2)
						+ "\","; // 最高温度
				result += "\"mintemp\":\"" + (Double.valueOf(minTemp1) > Double.valueOf(minTemp1) ? minTemp2 : minTemp1)
						+ "\",";// 最低温度
				result += "\"winds1\":\"" + windS1 + "\",";
				result += "\"winds2\":\"" + windS2 + "\",";
				result += "\"windd1\":\"" + windD1 + "\",";
				result += "\"windd2\":\"" + windD1 + "\",";
				result += "\"tq1\":\"" + weather1 + "\",";
				result += "\"tq2\":\"" + weather2 + "\"";
				result += "},";
				if (!weather1.equals(weather2)) {
					strWeather = weather1 + "转" + weather2;
				} else {
					strWeather = weather1;
				}
			}
			if (result.endsWith(",")) {
				result = result.substring(0, result.length() - 1);
			}
			result = result + "]";
			maxResult += "{\"maxMaxTemp\":\"" + maxTemp + "\"," + "\"minMinTemp\":\"" + minTemp + "\","
					+ "\"maxHumid\":\"" + maxHumid + "\"," + "\"TEM\":\"" + strWeather + "\"}]";
			temp = result + "|" + maxResult;
		} else {
			result += "{";
			result += "\"stationName\":\"" + "\",";
			result += "\"pic1\":\"" + "\",";
			result += "\"pic2\":\"" + "\",";
			result += "\"maxTemp\":\"" + maxTemp + "\","; // 最高温度
			result += "\"minTemp\":\"" + minTemp + "\",";// 最低温度
			result += "\"windS1\":\"" + "\",";
			result += "\"windS2\":\"" + "\",";
			result += "\"windD1\":\"" + "\",";
			result += "\"windD2\":\"" + "\",";
			result += "\"tq1\":\"" + "\",";
			result += "\"tq2\":\"" + "\"";
			result += "},";
			maxResult += "{\"maxMaxTemp\":\"" + Math.round(maxTemp) + "\"," + "\"minMinTemp\":\"" + Math.round(minTemp)
					+ "\"," + "\"maxHumid\":\"" + Math.round(maxHumid) + "\"," + "\"TEM\":\"" + strWeather + "\"}]";
			result = result + "]";
			temp = result + "|" + maxResult;
		}

		return temp;
	}

	// 小时负荷实况最新时间
	@RequestMapping("/getHourPowerTime")
	@ResponseBody
	public String getHourPowerTime() {
		Date date = hourPowerServiceImpl.getHourPowerTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		temp = sdf.format(date);
		return temp;
	}

	// 文档检索weatherMonitor
	@RequestMapping("/fileHourPowerLoad")
	@ResponseBody
	public List<DocFile> fileHourPowerLoad(HttpServletRequest request) {
		String strStartTime = request.getParameter("StartTime") + " 00:00";
		String strEndTime = request.getParameter("EndTime") + " 23:59";
		List<DocFile> list = hourPowerServiceImpl.fileHourPowerLoad(strStartTime, strEndTime, "hour");
		for (DocFile df : list) {
			String serviceFilePath = "";
			// 下载
			String fileName = df.getFileName();
			String collectionName = "";
			if(fileName.contains("doc")){
				collectionName = "doc_file";
			}else if(fileName.contains("pdf")){
				collectionName = "pdf_file";
			}
			String path = request.getContextPath();
			String basePath = DbConfig.IP + path
					+ "/Temp/PowerProduct/";
			String serviceUrl = basePath + fileName;
			String urlpath ;
			if (operatingSystem.equals("Windows")){
				 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\PowerProduct\\";
			}else {
				 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/PowerProduct/";
			}

			serviceFilePath = urlpath + fileName;// 服务器文件
			FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
			FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
			// 如果目录中不存在文件，下载雷达文件到temp目录
			File serviceFile = new File(serviceFilePath);// 服务器文件
			if (!serviceFile.exists()) {// 把文件上传到服务器
				Map<String, Object> queryMap = new HashMap<String, Object>();
				queryMap.put("id", df.getId());
				queryMap.put("table_name", "power_product");
				queryMap.put("advCode", DbConfig.advCode);
				queryMap.put("collectionName", collectionName);
				byte[] data = ms.selectData(queryMap);
				if (data == null) {
					serviceFilePath = "";
				} else {
					FileUtil.bytesToFile(data, serviceFilePath);
				}
			}
			if (!serviceFilePath.equals("")) {
				serviceFilePath = serviceUrl;
			}

			String productPath = serviceFilePath;
			//添加预报文档的路径路径
			df.setFilePath(productPath);
		}
		return list;
	}

	// 文档查看doc
	@RequestMapping("/ShowDoc")
	@ResponseBody
	public String ShowDoc(HttpServletRequest request) throws Exception {
		String id = request.getParameter("id");// 获取编号
		String docpath = request.getParameter("Path");// 获取前台文档路径

		String urlpath ;
		if (operatingSystem.equals("Windows")){
			 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\HourPowerLoad\\";// 临时文件目录
		}else {
			 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/HourPowerLoad/";// 临时文件目录
		}

		String path = request.getContextPath();
		String basePath = DbConfig.IP + path;
		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

		String fileName = docpath.split("\\\\")[docpath.split("\\\\").length - 1];// 文件名
		String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
		String servicePath = "";// 服务器文件
		if (doctype.contains("doc")) {
			String localPath = urlpath + fileName;
			String pdfPath = urlpath + fileName.replace(doctype, "pdf");
			File pdfFile = new File(pdfPath);
			if (pdfFile.exists()) {
				if (operatingSystem.equals("Windows")){
					servicePath = "\\Temp\\HourPowerLoad\\" + fileName.replace(doctype, "pdf");
				}else {
					servicePath = "/Temp/HourPowerLoad/" + fileName.replace(doctype, "pdf");
				}

				servicePath = basePath+servicePath;
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", id);
				map.put("table_name", "power_product");
				map.put("collectionName", "doc_file");
				map.put("advCode", DbConfig.advCode);
				byte[] data = ms.selectData(map);
				FileUtil.bytesToFile(data, localPath);
				// 下载doc文件
				if (data == null) {
					return "";
				}
				File localFile = new File(localPath);// 本地文件
				if (localFile.exists()) {
					try {
						Word2PdfUtil.doc2pdf(localPath, pdfPath);
						if (operatingSystem.equals("Windows")){
							servicePath = "\\Temp\\HourPowerLoad\\" + fileName.replace(doctype, "pdf");
						}else {
							servicePath = "/Temp/HourPowerLoad/" + fileName.replace(doctype, "pdf");
						}
						servicePath = basePath+servicePath;
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		servicePath = servicePath.replace("\\", "/");
		return servicePath;
	}

	// txt查看
	@RequestMapping(value = "/watchtxt")
	@ResponseBody
	public String ReadTxt(HttpServletRequest request) throws Exception {
		String id = request.getParameter("id");// 获取编号
		String path = request.getParameter("Path");// 获取前台文档路径
		String urlpath ;
		if (operatingSystem.equals("Windows")){
			 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\HourPowerTxt\\";// 临时文件目录
		}else {
			 urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/HourPowerTxt/";// 临时文件目录
		}


		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

		String fileName = path.split("\\\\")[path.split("\\\\").length - 1];// 文件名
		String txttype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
		String result = "";// 服务器文件
		if (txttype.contains("txt")) {
			String txtPath = urlpath + fileName;
			File txtFile = new File(txtPath);
			if (txtFile.exists()) {
				result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", id);
				map.put("table_name", "power_product");
				map.put("collectionName", "txt_file");
				map.put("advCode", DbConfig.advCode);
				byte[] data = ms.selectData(map);
				FileUtil.bytesToFile(data, txtPath);
				// 下载doc文件
				if (data == null) {
					return "";
				}
				result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
			}
		}
		return result;
	}

	// 小时负荷校验
	@RequestMapping("/hourPowerCheck")
	@ResponseBody
	public String hourPowerCheck(HttpServletRequest request) throws Exception {
		Hashtable<String, String> tempTable = new Hashtable<String, String>();// 实况温度
		Hashtable<String, String> humidTable = new Hashtable<String, String>();// 实况湿度
		Hashtable<String, String> powerTable = new Hashtable<String, String>();// 实况电力负荷
		String dateTime = request.getParameter("dateTime") + " 00:01";
		String dateTime2 = request.getParameter("dateTime") + " 23:59";
		List<HourPower> list1 = new ArrayList<HourPower>();
		// 电力预报
		List<HourPower> list = hourPowerServiceImpl.getHourForecast(dateTime, dateTime2);
		List<MsgMedium> mList = new ArrayList<MsgMedium>();
		if (DateTime.parseDate(dateTime).AddDays(30).before(DateTime.now())) {
			mList = hourPowerServiceImpl.getMsgMedium(dateTime, dateTime2, true);
		} else {
			mList = hourPowerServiceImpl.getMsgMedium(dateTime, dateTime2, false);
		}
		// 电力实况
		list1 = hourPowerServiceImpl.getPower(dateTime, dateTime2);
		for (MsgMedium m : mList) {
			Date date = new Date();
			date = m.getObservTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			tempTable.put(sdf.format(date), m.getDryBulbTemp());
			humidTable.put(sdf.format(date), m.getRelHumidity());
		}
		String ptd = "";
		for (HourPower hp : list1) {
			DateTime d = new DateTime(hp.getDataChar());
			ptd = d.toDateTimeString();
			powerTable.put(ptd, hp.getLoad());
		}
		String tableData = "[";
		String xValue = "[";
		String yValue = "";
		String dlYbVal = "[";// 电力预报
		String dlSkVal = "[";// 电力实况
		String tempVal = "[";// 温度实况
		String humidVal = "[";// 湿度实况

		for (HourPower hp : list) {
			DateTime d = new DateTime(hp.getDataChar());
			String dateChar = d.toDateTimeString();
			double dif;
			if(hp!=null&&hp.getLoad()!=null&&powerTable.get(dateChar)!=null&&powerTable.get(dateChar).length()>0){
				dif = Double.valueOf(hp.getLoad()) - Double.valueOf(powerTable.get(dateChar));
				tableData += "{\"dateChar\":\"" + d.GetHour() + "\",\"powerLoad\":\"" + hp.getLoad() + "\",\"powerSk\":\""
						+ powerTable.get(dateChar) + "\",\"dif\":\"" + Math.round(dif * 100) / 100 + "\"},";
				xValue += "'" + d.GetHour() + "',";
				dlYbVal += hp.getLoad() + ",";
				dlSkVal += powerTable.get(dateChar) + ",";
				tempVal += tempTable.get(dateChar) + ",";
				humidVal += humidTable.get(dateChar) + ",";
			}
		}
		if (tableData.length() > 1) {
			tableData = tableData.substring(0, tableData.length() - 1);
		}
		tableData += "]";
		if (xValue.length() > 1) {
			xValue = xValue.substring(0, xValue.length() - 1);
		}
		xValue += "]";
		if (dlYbVal.length() > 1) {
			dlYbVal = dlYbVal.substring(0, dlYbVal.length() - 1);
		}
		dlYbVal += "]";
		if (dlSkVal.length() > 1) {
			dlSkVal = dlSkVal.substring(0, dlSkVal.length() - 1);
		}
		dlSkVal += "]";
		if (tempVal.length() > 1) {
			tempVal = tempVal.substring(0, tempVal.length() - 1);
		}
		tempVal += "]";
		if (humidVal.length() > 1) {
			humidVal = humidVal.substring(0, humidVal.length() - 1);
		}
		humidVal += "]";
		yValue = "[{\"name\":\"预报负荷\",\"data\":" + dlYbVal + "},{\"name\":\"实况负荷\",\"data\":" + dlSkVal
				+ "},{\"name\":\"实况温度\",\"data\":" + tempVal + "},{\"name\":\"实况湿度\",\"data\":" + humidVal + "}]";
		temp = tableData + "|" + xValue + "|"
				+ yValue /*
							 * + "|" +
							 * GetDayForecast(Convert.ToDateTime(dateTime).
							 * ToString("yyyy-MM-dd"))
							 */;
		return temp;
	}

	/* 导出excel */
	@RequestMapping("/export")
	@ResponseBody
	public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取数据
		String dateTime = request.getParameter("dateTime");
		List<HourPower> hpList = hourPowerServiceImpl.hourPowerLoad(dateTime);

		// excel标题
		String[] title = { "日期", "负荷" };

		// excel文件名
		String fileName = "逐小时电力负荷预报表.xls";

		// sheet名
		String sheetName = "电力负荷预报表";

		String[][] content = new String[hpList.size()][];
		
		for (int i = 0; i < hpList.size(); i++) {
			content[i] = new String[title.length];
			HourPower obj = hpList.get(i);
	        SimpleDateFormat sdff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			content[i][0] = sdff.format(obj.getDataChar());
			content[i][1] = obj.getLoad().toString();
		}

		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

		// 响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/* 导出excel */
	@RequestMapping("/exportcheck")
	@ResponseBody
	public void exportcheck(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取数据
		String dateTime = request.getParameter("dateTime") + " 00:01";
		String dateTime2 = request.getParameter("dateTime") + " 23:59";
		// 电力预报
		List<HourPower> hpList = hourPowerServiceImpl.getHourForecast(dateTime, dateTime2);
		Hashtable<String, String> powerTable = new Hashtable<String, String>();// 实况电力负荷
		List<HourPower> list1 = new ArrayList<HourPower>();
		// 电力实况
		list1 = hourPowerServiceImpl.getPower(dateTime, dateTime2);
		String ptd = "";
		for (HourPower hp : list1) {
			DateTime d = new DateTime(hp.getDataChar());
			ptd = d.toDateTimeString();
			powerTable.put(ptd, hp.getLoad());
		}

		// excel标题
		String[] title = { "小时", "预报负荷", "实况负荷", "差值" };

		// excel文件名
		String fileName = "逐小时电力负荷校验表.xls";

		// sheet名
		String sheetName = "电力负荷校验表";

		String[][] content = new String[hpList.size()][];
		
		for (int i = 0; i < hpList.size(); i++) {
			content[i] = new String[title.length];
			HourPower obj = hpList.get(i);
	        DateTime d = new DateTime(obj.getDataChar());
			String dateChar = d.toDateTimeString();
			if(powerTable.get(dateChar)!=null){
				double dif = Double.valueOf(obj.getLoad()) - Double.valueOf(powerTable.get(dateChar));
				content[i][0] = d.GetHour() + "";
				content[i][1] = obj.getLoad().toString();
				content[i][2] = powerTable.get(ptd);
				content[i][3] = Math.round(dif * 100) / 100 + "";
			}
		}

		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

		// 响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	// 发送响应流方法
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
